import React, { useEffect, useRef, useState } from "react";
import styles from "./css/chat.module.css";
import Navbar from "../../../components/navbar";
import { Button, TextArea, Toast } from "antd-mobile";
import ChatLeft from "./components/ChatLeft";
import ChatRight from "./components/ChatRight";
import { useSend } from "../../../hooks";
function Index() {
  const [list, setList] = useState([]);
  const [umsg, setUmsg] = useState("");
  const socket = useSend("wss://api-ticket.liulongbin.top", (msg) => {
    console.log(msg);
    setList((prev) => [
      ...prev,
      { type: "AI", message: msg.replaceAll("{br}", "<br />") },
    ]);
  });
  const send = () => {
    if (umsg.trim().length === 0) {
      Toast.show({
        content: "消息发送不能为空！",
      });
    }
    socket.current.emit("chatWithServer", umsg);
    setList((prev) => [...prev, { type: "User", message: umsg }]);
    setTimeout(() => setUmsg(""));
  };
  let bottom = useRef(null);
  useEffect(() => {
    const dom = bottom.current.lastElementChild;
    if (!dom) return;
    dom.scrollIntoView();
  }, [list]);

  return (
    <div className={styles.box}>
      <Navbar title="在线客服" />
      <div ref={bottom}>
        {list.map((item, i) => {
          return item.type === "AI" ? (
            <ChatLeft key={i} msg={item.message} />
          ) : (
            <ChatRight key={i} msg={item.message} />
          );
        })}
      </div>
      <div className={styles.footer}>
        <TextArea
          placeholder="请输入"
          value={umsg}
          onEnterPress={send}
          onChange={(val) => setUmsg(val)}
        />
        <Button
          onClick={send}
          disabled={umsg.trim().length = 0}
          className={styles.btns}
          color="primary"
        >
          发送
        </Button>
      </div>
    </div>
  );
}

export default Index;
